package com.example.glkotlin.adapter

import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.example.glkotlin.R
import com.example.glkotlin.bean.MsgBean

class MsgAdapter (private val messages : List<MsgBean>) : RecyclerView.Adapter<ViewHolder>(){
    inner class ViewHolderRec(view : View): ViewHolder(view) {
       val recMsg = view.findViewById<TextView>(R.id.rec_message)
    }

    inner class ViewHolderSend(view : View): ViewHolder(view) {
        val sendMsg = view.findViewById<TextView>(R.id.send_message)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        if (viewType == MsgBean.TYPE_RECEIVED) {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.message_adapter_rec_item, parent, false)
            ViewHolderRec(view)
        } else  {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.message_adapter_send_item, parent, false)
            ViewHolderSend(view)
        }

    override fun getItemCount(): Int {
        return messages.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val message = messages[position]
        when(holder) {
            is ViewHolderRec -> holder.recMsg.text = message.msg
            is ViewHolderSend -> holder.sendMsg.text = message.msg
            else -> Log.e(TAG, "onBindViewHolder holder type is error")
        }
    }

    override fun getItemViewType(position: Int): Int {
        return messages[position].type
    }

    companion object {
        const val TAG = "MsgAdapter"
    }

}

